import Vue from 'vue'
import axios from 'axios'
import store from '../store'
import router from '../router'

axios.defaults.baseURL = "http://139.155.244.118:8820/";
Vue.prototype.$ajax = axios;

//request 拦截器
axios.interceptors.request.use(function(config) {
  var token = sessionStorage.getItem("token");
  if (token) {
    config.headers.Authorization = token;
  }

  if (config.method != 'get') {
    var sendData = new FormData();
    var data = config.data;
    Object.keys(data).forEach(key => {
      sendData.append(key, data[key]);
    });
    config.data = sendData;
  }
  return config;
}, function(error) {
  return Promise.reject(error);
});

// response 拦截器
axios.interceptors.response.use(
  response => {
    return response;
  },
  error => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          sessionStorage.removeItem("token"); //清除本地token串
          //返回登录页面
          router.replace({
            path: "/",
          });
      }
    }
    return Promise.reject(error.response);
  }
);
